package club.caihappy.server.config.security.component;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collection;

/**
 * 权限控制
 * 判断用户角色
 * Created by DELL on 2022/5/21
 **/
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {

        //获取当前用户所拥有的角色（通过用户pojo中的getAuthority）
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        System.out.println(Arrays.toString(authorities.toArray()));
        //遍历请求url所需角色，根据CustomFilter返回值
        for (ConfigAttribute configAttribute : collection) {
            String needRole = configAttribute.getAttribute();
            //判断url是否只需要登录就能访问
            if ("ROLE_LOGIN".equals(needRole)) {
                //判断是否登录，登录了直接放回就行
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException("尚未登录，请登录");
                } else {
                    return;
                }
            }
            //判断用户角色中（通过用户pojo中的getAuthority）是否有url所需角色
            for (GrantedAuthority authority : authorities) {
                if (authority.getAuthority().equals(needRole)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
